package com.javalong.affairs.adapter;

import java.util.ArrayList;
import java.util.List;

import android.R.bool;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

import com.javalong.affairs.R;
import com.javalong.affairs.model.User;

public class GranterAdapter extends BaseAdapter {
	private List<User> selectedUsers;

	public GranterAdapter(Context context, List<User> userList) {
		super(context, userList);
		selectedUsers = new ArrayList<User>();
	}

	public List<User> getSelectedUsers() {
		return selectedUsers;
	}

	@Override
	public void notifyDataSetChanged() {
		super.notifyDataSetChanged();
		selectedUsers.clear();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final User user = (User) getItem(position);
		ViewHolder holder;
		if (convertView != null) {
			holder = (ViewHolder) convertView.getTag();
		} else {
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.item_receiver, null);
			holder.tv_user = (TextView) convertView.findViewById(R.id.tv_user);
			holder.cb_user = (CheckBox) convertView.findViewById(R.id.cb_user);
			convertView.setTag(holder);
		}

		if (user != null) {
			holder.tv_user.setText(user.userName);

			holder.cb_user
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							if (isChecked) {
								if (!selectedUsers.contains(user)) {
									selectedUsers.add(user);
								}
							} else {
								if (selectedUsers.contains(user)) {
									selectedUsers.remove(user);
								}
							}
						}
					});
			if (selectedUsers.contains(user)) {
				holder.cb_user.setChecked(true);
			} else {
				holder.cb_user.setChecked(false);
			}
		}
		return convertView;
	}

	class ViewHolder {
		CheckBox cb_user;
		TextView tv_user;
	}
}
